package com.dingyx.ps.util;

import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;

/**
 * <脱敏功能包>
 *
 * @author ZhangYiMing
 * @version 1.0.0
 * @date 2021/5/13
 */
public class DesensitizationUtil {

    /*
     * < 手机号脱敏 >
     * @Params [phoneNumber]
     * @return java.lang.String
     * @author zym
     * @date 2021/5/13 18:07
     * @version v1.0.0
     */
    public static String desensitizedPhoneNumber(String phoneNumber) {
        if (StringUtils.isNotEmpty(phoneNumber)) {
            phoneNumber = phoneNumber.replaceAll("(\\w{3})\\w*(\\w{4})", "$1****$2");
        }
        return phoneNumber;
    }

    /*
     * < 身份证脱敏 >
     * @Params [idNumber]
     * @return java.lang.String
     * @author zym
     * @date 2021/5/13 18:07
     * @version v1.0.0
     */
    public static String desensitizedIdNumber(String idNumber) {
        if (!Strings.isNullOrEmpty(idNumber)) {
            if (idNumber.length() == 15) {
                idNumber = idNumber.replaceAll("(\\w{6})\\w*(\\w{3})", "$1******$2");
            }
            if (idNumber.length() == 18) {
                idNumber = idNumber.replaceAll("(\\w{6})\\w*(\\w{3})", "$1*********$2");
            }
        }
        return idNumber;
    }

    /*
     * < 地址脱敏 >
     * @Params [address]
     * @return java.lang.String
     * @author zym
     * @date 2021/5/13 18:07
     * @version v1.0.0
     */
    public static String desensitizedAddress(String address) {
        if (!Strings.isNullOrEmpty(address)) {
            return StringUtils.left(address, 3).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(address, address.length() - 11), StringUtils.length(address), "*"), "***"));
        }
        return address;
    }

    /*
     * < 银行卡脱敏 >
     * @Params [bankAcct]
     * @return java.lang.String
     * @author zym
     * @date 2021/5/13 19:32
     * @version v1.0.0
     */
    public static String encryptBankAcct(String bankAcct) {
        if (bankAcct == null) {
            return "";
        }
        return replaceBetween(bankAcct, 6, bankAcct.length() - 4, null);
    }

    private static String replaceBetween(String sourceStr, int begin, int end, String replacement) {
        if (sourceStr == null) {
            return "";
        }
        if (replacement == null) {
            replacement = "*";
        }
        int replaceLength = end - begin;
        if (StringUtils.isNotBlank(sourceStr) && replaceLength > 0) {
            StringBuilder sb = new StringBuilder(sourceStr);
            sb.replace(begin, end, StringUtils.repeat(replacement, replaceLength));
            return sb.toString();
        } else {
            return sourceStr;
        }
    }
}
